//
//  NetworkHelper.m
//  TaurusXi
//
//  Created by xicheng on 15/12/8.
//  Copyright © 2015年 xicheng. All rights reserved.
//

#import "NetworkHelper.h"
#import "NetworkTask.h"
#import "AFHTTPRequestOperationManager.h"
#import "UserHelper.h"
#import "MD5_Utils.h"
#import "CodeStatus.h"

@implementation NetworkHelper

+ (instancetype)sharedInstance{
  static id sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[self alloc] init];
  });
  return sharedInstance;
}


- (void)addTask:(NetworkTask *)task  WithSuccessBlock:(PassValueBlock)successBlock AndErrorBlock:(PassErrorBlock)errorBlock{
  
  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", nil];
  //获取设备标示
//  [manager.requestSerializer setValue:@"UA" forHTTPHeaderField:@"UA"];
  
  //  1、userId用户id 未登陆为空。
  //  2、t 时间戳
  //  3、sign安全校验签名,用来防止伪造请求。
  int currentTime = (int)[[NSDate date] timeIntervalSince1970];
  NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
  [params setObject:[UserHelper shareUserInstance].userId forKey:@"userId"];
  [params setObject:[NSString stringWithFormat:@"%d",currentTime] forKey:@"t"];
  [params setObject:[self getSignWithTimestamp:currentTime] forKey:@"sign"];
  [params addEntriesFromDictionary:task.params];
  manager.requestSerializer.timeoutInterval = 10;
  if (task.method == HttpMethodGet) {
    [manager GET:task.httpURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
      if (successBlock) {
        successBlock(responseObject);
      }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
      if (errorBlock) {
        errorBlock(nil,error);
      }
    }];
  }else if (task.method == HttpMethodPost){
    [manager POST:task.httpURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
      NSLog(@"参数_%@_成功:%@",params,responseObject);
      
      if ([self isSuccessResultFlagWithData:responseObject]) {
        if (successBlock) {
          successBlock(responseObject);
        }
      }else{
        if (errorBlock) {
          NSError *aError = [NSError errorWithDomain:@"业务异常" code:12123 userInfo:nil];
          errorBlock(responseObject,aError);
        }
      }

    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
      NSLog(@"错误:%@",error);
      if (errorBlock) {
        errorBlock(nil,error);
      }
    }];
  }
    
}


-(BOOL)isSuccessResultFlagWithData:(id)object{

  if (![object isKindOfClass:[NSDictionary class]]) {
    return NO;
  }
  id codeId = [object objectForKey:@"code"];
  NSInteger codeInterger = -1;
  if ([codeId isKindOfClass:[NSString class]] || [codeId isKindOfClass:[NSNumber class]] ) {
    codeInterger = [codeId integerValue];
  }
  if (codeInterger == kSUCCESS) {
    return YES;
  }
  return NO;
}


-(NSString *)getSignWithTimestamp:(int)timestamp{
  NSString *sign__ = [NSString stringWithFormat:@"%@%d%@",[UserHelper shareUserInstance].userId,timestamp,@"APPKEY2015JNZUO" ];
  return [MD5_Utils md5HexDigest:sign__];
  
}
@end
